package com.wiserun.RestFul.RestfulAction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.JsonObject;
import com.wiserun.RestFul.model.BeisenToken;
import com.wiserun.RestFul.service.BeisenApiTokenService;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.patterns.IToken;
import org.aspectj.weaver.patterns.ITokenSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;

@Service
public class ClientAction {

    private static final Logger logger = LoggerFactory.getLogger(ClientAction.class);
    //从配置文件yml中获取北森的参数
    @Value("${beisenToken.grant_type}")
    private String grant_type = "";//必填参数grant_type
    @Value("${beisenToken.app_key}")
    private String app_key = "";
    @Value("${beisenToken.app_secret}")
    private String app_secret = "";
    @Value("${restful.tokenpath}")
    private String tokenpath = "";
    @Value("${restful.systemIP}")
    private String systemIP = "";

    @Autowired
    private BeisenApiTokenService beisenApiTokenService;


    /**
     * 获取北森组织机构信息
     *
     * @param parm
     * @return 返回获取到的接口对象，如果返回null则表示接口调用异常
     */
    public JSONObject BeisenOrganization(JSONObject parm) {
        HttpClient httpClient = HttpClients.createDefault();
        String apiURL = parm.getString("apiURL");
        String token = parm.getString("token");
        HttpPost request = new HttpPost(apiURL);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(300000).setConnectionRequestTimeout(300000).setSocketTimeout(300000).build();
        request.setConfig(requestConfig);
        JSONObject jsonObject = new JSONObject();//返回的json数据
        HttpEntity entity;
        HttpResponse execute;
        String result = "";
        // 浏览器表示
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0");
        // 传输的类型 不正确时会报错
        request.addHeader("Content-Type", "application/json;charset=utf-8");
        request.addHeader("Authorization", "Bearer " + token);
        try {
            // 创建请求参数
            JSONObject json = new JSONObject();
            //组装json参数
            for (Map.Entry<String, Object> entry : parm.entrySet()) {
                logger.info("ClientAction.ClientPost.param.key==>" + entry.getKey() + "#param.value==>" + (Object) entry.getValue());
                if (!entry.getKey().equals("apiURL")) {
                    json.put(entry.getKey(), (Object) entry.getValue());
                }
            }
            StringEntity entityParam = new StringEntity(json.toJSONString(), "utf-8");
            request.setEntity(entityParam);
            //执行请求
            execute = httpClient.execute(request);
            entity = execute.getEntity();
            result = EntityUtils.toString(entity, "GBK");
            logger.info("北森接口返回的json数据==>" + result);
            jsonObject = JSON.parseObject(result);
        } catch (Exception e) {
			logger.info("同步北森组织机构时--访问北森服务器超时");
            e.printStackTrace();
        }
        //return result;
        return jsonObject;
    }

    //获取北森员工信息
    public JSONObject BeisenUsers(JSONObject parm) {
        HttpClient httpClient = HttpClients.createDefault();
        String apiURL = parm.getString("apiURL");
        String token = parm.getString("token");
        HttpPost request = new HttpPost(apiURL);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(300000).setConnectionRequestTimeout(300000).setSocketTimeout(300000).build();
        request.setConfig(requestConfig);
        HttpResponse execute;
        String result = "";
        JSONObject jsonObject = null;
        // 浏览器表示
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0");
        // 传输的类型 不正确时会报错
        request.addHeader("Content-Type", "application/json;charset=utf-8");
        request.addHeader("Authorization", "Bearer " + token);
        try {
            // 创建请求参数
            JSONObject json = new JSONObject();
            //组装json参数
            for (Map.Entry<String, Object> entry : parm.entrySet()) {
                logger.info("ClientAction.ClientPost.param.key==>" + entry.getKey() + "#param.value==>" + (Object) entry.getValue());
                if (!entry.getKey().equals("apiURL")) {
                    json.put(entry.getKey(), (Object) entry.getValue());
                }
            }
            //========循环自动加入结束=====
            StringEntity entityParam = new StringEntity(json.toJSONString(), "utf-8");
            request.setEntity(entityParam);
            //执行请求
            execute = httpClient.execute(request);
            HttpEntity entity = execute.getEntity();


            result = EntityUtils.toString(entity, "GBK");
            logger.info("北森接口返回的json数据==>" + result);
            jsonObject = JSON.parseObject(result);
        } catch (Exception e) {
			logger.info("同步北森用户时--访问北森服务器超时");
            e.printStackTrace();
        }
        //return result;
        return jsonObject;
    }

    //调用北森token接口,发起调用逻辑处理
    public JSONObject BeisenToken(JSONObject parm) {
        HttpClient httpClient = HttpClients.createDefault();
        String apiURL = parm.getString("apiURL");
        HttpPost request = new HttpPost(apiURL);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(300000).setConnectionRequestTimeout(300000).setSocketTimeout(300000).build();
        request.setConfig(requestConfig);
        HttpResponse execute;
        String result = "";
        JSONObject jsonObject = null;
        // 浏览器表示
        request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0");
        // 传输的类型 不正确时会报错
        request.addHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            // 创建请求参数
            JSONObject json = new JSONObject();
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            //填充form表单的参数
            for (Map.Entry<String, Object> entry : parm.entrySet()) {
                //封装grant_type 、 app_key 、app_secret 参数
                if (entry.getKey().equals("grant_type") || entry.getKey().equals("app_secret") ||
                        entry.getKey().equals("app_key")) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
                }
            }
            //logger.error("封装后的参数=====>"+pairs.toString());
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
            //设置参数
            request.setEntity(urlEncodedFormEntity);
            //执行请求
            execute = httpClient.execute(request);
            HttpEntity entity = execute.getEntity();
            //logger.error("返回的数据========>"+entity);
            result = EntityUtils.toString(entity, "GBK");
            //logger.error("转换成String的数据=======>"+result);
            jsonObject = JSON.parseObject(result);
            jsonObject.put("create_date", new Date());
        } catch (Exception e) {
			logger.info("获取北森token时----访问北森服务器超时");
            e.printStackTrace();
        }
        //return result;
        return jsonObject;
    }

    /**
     * 北森token存入数据库
     *
     * @return TOKEN信息
     */
    public String createToken() {
        // logger.info("RestfulAction.testRestFul.restfulAuth");
        String apiURL = systemIP + tokenpath;
        //构成传入参数
        JSONObject parm = new JSONObject();
        parm.put("apiURL", apiURL);
        parm.put("grant_type", grant_type);
        parm.put("app_key", app_key);
        parm.put("app_secret", app_secret);
        //放入post方法执行
        JSONObject jsonObject = this.BeisenToken(parm);
        //将返回的jsonobject 转化成 实体类对象
        JSONObject beisenToken_json = JSONObject.parseObject(jsonObject.toString());
        BeisenToken beisenToken = JSON.toJavaObject(beisenToken_json, BeisenToken.class);
        logger.info("转换后的实体对象======>" + beisenToken);
        //String access_token=jsonObject.getString("access_token");
        //JSONObject data=jsonObject.getJSONObject("data");
        //String token_type=jsonObject.getString("token_type");
        //todo 将获取到的北森接口数据存入到pncs数据库
        int count = beisenApiTokenService.addToken(beisenToken);
        if (count == 1) {
            jsonObject.put("是否存储pncs数据库", "存储成功");
            return jsonObject.getString("access_token");//返回token
        } else {
            jsonObject.put("是否存储pncs数据库", "存储失败");
            return null;
        }
    }
}
